<template>
  <el-dialog
    :title="(isEdit ? '修改' : '添加') + '品牌'"
    v-model="dialogVisible"
    @close="cancel"
  >
    <el-form
      label-width="120px"
      :model="form"
      ref="formRef"
      :rules="formRules"
      style="width: 90%"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input v-model="form.tmName"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo" prop="logoUrl">
        <el-upload
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          @success="handleUploadSuccess"
          :before-upload="beforeUpload"
          class="uploader"
        >
          <img v-if="form.logoUrl" :src="form.logoUrl" class="logo-img" />
          <el-icon v-else class="uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">提 交</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import type { trademark } from '@/api/product/trademark/type'
import { addTradeMark, updateTradeMark } from '@/api/product/trademark'
import type { FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
const props = defineProps<{
  visible: boolean
  form: trademark
}>()
const emit = defineEmits(['update:visible', 'update:form'])

let dialogVisible = ref<boolean>(false)
const formRef = ref()
const form = reactive<trademark>({
  id: undefined,
  tmName: '',
  logoUrl: ''
})
const logoValidate = (rule: any, value: string, callback: any) => {
  if (!value) {
    return callback(new Error('请上传品牌logo'))
  }
  callback()
}
const formRules = reactive<FormRules<trademark>>({
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 5, message: '品牌名称长度为2到5个字符', trigger: 'change' }
  ],
  logoUrl: [{ required: true, validator: logoValidate }]
})
const isEdit = ref<boolean>(false)

const handleUploadSuccess = (res: any) => {
  if (res.code === 200) {
    form.logoUrl = res.data
    formRef.value.clearValidate('logoUrl')
  } else {
    ElMessage.error('上传失败')
  }
}

const beforeUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('Logo图片只能是 JPG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('Logo图片大小不能超过 2MB!')
    return false
  }
}

const cancel = () => {
  emit('update:visible', false)
}
const confirm = async () => {
  const api = isEdit.value ? updateTradeMark : addTradeMark
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      api(form)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success((isEdit.value ? '修改' : '添加') + '成功')
            emit('update:form')
          } else {
            ElMessage.error(res.data)
          }
        })
        .catch(() => {})
    }
  })
}

watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal
    isEdit.value = false
    nextTick(() => {
      formRef.value.resetFields()
      form.id = undefined

      if (props.form.id) {
        Object.assign(form, props.form)
        isEdit.value = true
      }
    })
  }
)
</script>
<script lang="ts">
export default {
  name: 'EditDialog'
}
</script>
<style lang="scss" scoped>
.uploader {
  .logo-img {
    width: 178px;
    height: 178px;
    display: block;
  }
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  :deep(.el-icon.uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
